#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   auth.py
@Time    :   2024/01/02 11:06:06
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from datetime import datetime
from ninja import Field,Schema
from ninja.security import HttpBearer
from ninja.errors import HttpError
from typing import Any, List
from django.db.models import QuerySet
from ninja.types import DictStrAny
from ninja.pagination import PaginationBase

from utils.jwt import Jwt
from system.models import Users
from big_event.settings import SECRET_KEY


def get_user_info_from_token(request):
    # 从请求中获取token
    token = request.META.get("HTTP_AUTHORIZATION")
    # 将token按空格分割并取第二个元素
    token = token.split(" ")[1]
    # 创建Jwt对象
    jwt = Jwt(SECRET_KEY)
    # 使用SECRET_KEY和token解码获取值
    value = jwt.decode(SECRET_KEY, token)
    # 获取解码后的payload作为用户信息
    user_info = value.payload
    # 返回用户信息
    return user_info


class BaseFilters(Schema):
    creator_id: int = Field(None, alias="creator_id")
    
    
class MyPagination(PaginationBase):
    class Input(Schema):
        pageSize: int = Field(10, gt=0)
        pageNum: int = Field(1, gt=-1)

    class Output(Schema):
        items: List[Any]
        total: int

    def paginate_queryset(
            self,
            queryset: QuerySet,
            pagination: Input,
            **params: DictStrAny,
    ) -> Any:
        offset = pagination.pageSize * (pagination.pageNum - 1)
        limit: int = pagination.pageSize
        return {
            "page": offset,
            "limit": limit,
            "items": queryset[offset: offset + limit],
            "total": self._items_count(queryset),
        }


def data_permission(request, filters: BaseFilters):
    """
    根据请求和过滤器获取数据权限
    Args:
        request: 请求对象
        filters: 过滤器对象
    Returns:
        返回过滤器对象，包含用户的数据权限
    """
    # 从请求中获取用户信息
    user_info = get_user_info_from_token(request)
    # 如果用户是超级管理员,返回过滤器对象
    if user_info['is_superuser']: 
        return filters
    # 设置过滤器的创建者为当前用户  
    filters.creator_id = user_info['id']
    return filters 


class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        jwt = Jwt(SECRET_KEY)
        value = jwt.decode(SECRET_KEY, token)
        time_now = int(datetime.now().timestamp())
        # 判断token是否过期
        if value.valid_to >= time_now:
            token_user = value.payload
            token_user_id = token_user['id']
            user = Users.objects.get(id=token_user_id)
            # 判断用户是否存在
            if user:
                # 判断用户是否有权限访问该资源
                if user.status:
                    return token
                else:
                    raise HttpError(401, '用户已被禁用')
            else:
                raise HttpError(401, '用户不存在')
        else:
            raise TimeoutError(401, 'token时间过期')
